package com.qf.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.entity.Stock;
import com.qf.mapper.StockMapper;
import com.qf.service.StockService;
import com.qf.vo.StockParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

import java.util.List;

@Service
public class StockServiceeImpl extends ServiceImpl<StockMapper, Stock> implements StockService {

    @Autowired
    private TransactionTemplate template;

    /**
     * 事务的保存点
     *
     * @param list
     * @return
     */
    @Override
    public Boolean lockGoodsStock(List<StockParam> list) {
        return template.execute(new TransactionCallback<Boolean>() {
            @Override
            public Boolean doInTransaction(TransactionStatus status) {

                // 1.创建一个事务的保存点
                Object savepoint = status.createSavepoint();

                Boolean falg = true; // 默认是扣减成功
                for (StockParam stockParam : list) {
                    Integer stock = baseMapper.lockGoodsStock(stockParam);
                    if (stock <= 0) {
                        falg = false;
                        // 2.回滚事务到指定的保存点
                        status.rollbackToSavepoint(savepoint);
                        break;
                    }
                }
                return falg;
            }
        });
    }

    @Override
    public Boolean unLockGoodsStock(List<StockParam> list) {
        return template.execute(new TransactionCallback<Boolean>() {
            @Override
            public Boolean doInTransaction(TransactionStatus status) {
                Object savepoint = status.createSavepoint();
                for (StockParam stockParam : list) {
                    Integer stock = baseMapper.unLockGoodsStock(stockParam);
                    if (stock <= 0) {
                        status.rollbackToSavepoint(savepoint);
                        return false;
                    }
                }
                return true;
            }
        });
    }
}
